<?php
declare(strict_types=1);

namespace app\common\model\delivery;

use think\Model;

class SellerCommission Extends Model
{
    const SETTLETYPE=[
        'month'=>'独立分账',
        'money'=>'现金奖励',
        'persent'=>'比例提成',
    ];

    const ORDERTYPE=[
        'goodsorder'=>'商品下单'
    ];

    protected $type = [
        'createtime'  =>  'timestamp:Y-m-d H:i',
    ];

    public function customer()
    {
        return $this->hasOne(Customer::class,'id','store_id')->field('id,name');
    }

    public function channelorder()
    {
        return $this->hasOne(ChannelOrder::class,'id','order_id')->field('id,order_no,refuse_remark');
    }

    public function recharge()
    {
        return $this->hasOne(TowelPackageRecharge::class,'id','recharge_id',[]);
    }

    public static function commissionOrder($order)
    {
        $now=time();
        $customer=Customer::withJoin(['commission'],'left')->where(['customer_id'=>$order->customer_id])->find();
        if(!$customer || !$customer->seller_id || !$customer->commission){
            return;
        }
        $comm=self::where(['order_type'=>'goodsorder','order_id'=>$order->id])->find();
        if($comm){
            return;
        }
        $comm=new self();
        $comm->channel_id=$order->channel_id;
        $comm->customer_id=$order->customer_id;
        $comm->seller_id=$customer->seller_id;
        $comm->commission_type=$customer->commission->commission_type;
        $comm->order_type='goodsorder';
        $comm->order_id=$order->id;
        $money=0;
        if($customer->commission->commission_type=='persent'){
            $money=round($customer->commission->persent*$order->total_money*0.01,2);
        }
        if($customer->commission->commission_type=='month'){
            $money=$order->total_money;
        }
        if($customer->commission->commission_type=='money'){
            $money=$customer->commission->money;
        }
        $comm->money=$money;
        $comm->remark='【'.$customer['name'].'】下单'.($order->number-$order->refund_number).$order->goods->unit.$order->goods['name'];
        $comm->createtime=$now;
        $comm->save();
    }
}
